<script lang="ts" setup>
import type { FormInstance, UploadProps } from 'ant-design-vue';
import type { RuleObject } from 'ant-design-vue/es/form/interface';

import { nextTick, onMounted, reactive, ref, watch } from 'vue';

// 从ant-design-vue/icons-vue导入图标
import {
  BookOutlined,
  CommentOutlined,
  DeleteOutlined,
  EditOutlined,
  InboxOutlined,
  MoreOutlined,
  PlusOutlined,
  RobotOutlined,
  SearchOutlined,
  UploadOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
// 导入所有需要的组件
import {
  Button,
  Card,
  CardMeta,
  Col,
  Dropdown,
  Empty,
  Form,
  FormItem,
  Input,
  InputSearch,
  Menu,
  MenuItem,
  message,
  Modal,
  Row,
  Spin,
  Switch,
  Tag,
  Textarea,
  Upload,
} from 'ant-design-vue';

// 暂时使用相对路径导入API
import {
  createKnowledgeBase,
  deleteKnowledgeBase,
  getCarKnowledgeAnswer,
  getKnowledgeBaseList,
  searchKnowledgeBase,
  updateKnowledgeBase,
  uploadFileToKnowledgeBase,
} from '#/api';

// 知识库列表
const knowledgeBases = ref<any[]>([]);
const loading = ref(false);

// 表单相关
const modalVisible = ref(false);
const modalMode = ref<'create' | 'edit'>('create');
const formRef = ref<FormInstance>();
const statusChecked = ref(true);
const formState = reactive({
  id: '',
  name: '',
  description: '',
  status: 1,
});
// 定义表单验证规则
const formRules: Record<string, RuleObject[]> = {
  name: [{ required: true, message: '请输入知识库名称', trigger: 'blur' }],
};

// 上传文件相关
const uploadModalVisible = ref(false);
const currentKnowledgeBase = ref<any>(null);
const fileList = ref<any[]>([]);

// 知识问答相关
const queryModalVisible = ref(false);
const queryText = ref('');
const answering = ref(false);
const chatMessages = ref<any[]>([]);
const chatContainer = ref<HTMLElement | null>(null);

// 知识库搜索相关
const searchModalVisible = ref(false);
const searchText = ref('');
const searchResults = ref<any[]>([]);
const searchLoading = ref(false);

// 获取知识库列表
const fetchKnowledgeBases = async () => {
  loading.value = true;
  try {
    const data = await getKnowledgeBaseList();
    console.log('Knowledge base API response data:', data);

    // requestClient配置了responseReturn: 'data'，所以直接获取到的是API的data字段
    if (Array.isArray(data)) {
      knowledgeBases.value = data;
    } else {
      // 如果返回的不是数组，尝试从嵌套结构中获取
      knowledgeBases.value = Array.isArray(data?.data) ? data.data : [];
    }

    // 如果是空数组且请求成功，显示提示信息
    if (knowledgeBases.value.length === 0) {
      console.log('知识库列表为空，请创建新的知识库');
    } else {
      console.log('成功获取知识库列表，数量:', knowledgeBases.value.length);
    }
  } catch (error: any) {
    console.error('获取知识库列表失败:', error);
    message.error(error.message || '获取知识库列表失败');
    knowledgeBases.value = [];
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateModal = () => {
  modalMode.value = 'create';
  resetForm();
  modalVisible.value = true;
};

// 显示编辑对话框
const showEditModal = (kb: any) => {
  modalMode.value = 'edit';
  resetForm();
  formState.id = kb.id;
  formState.name = kb.name;
  formState.description = kb.description || '';
  formState.status = kb.status;
  statusChecked.value = kb.status === 1;
  modalVisible.value = true;
};

// 确认删除
const confirmDelete = (kb: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除知识库"${kb.name}"吗？此操作不可恢复。`,
    okText: '确认',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        await deleteKnowledgeBase(kb.id);
        message.success('删除成功');
        fetchKnowledgeBases();
      } catch (error: any) {
        message.error(error.message || '删除失败');
      }
    },
  });
};

// 重置表单
const resetForm = () => {
  formState.id = '';
  formState.name = '';
  formState.description = '';
  formState.status = 1;
  statusChecked.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 处理对话框确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate();

    const data = {
      name: formState.name,
      description: formState.description,
      status: formState.status,
    };

    if (modalMode.value === 'create') {
      await createKnowledgeBase(data);
      message.success('创建成功');
    } else {
      await updateKnowledgeBase(formState.id, data);
      message.success('更新成功');
    }

    modalVisible.value = false;
    fetchKnowledgeBases();
  } catch (error: any) {
    message.error(error.message || '操作失败');
  }
};

// 处理对话框取消
const handleModalCancel = () => {
  modalVisible.value = false;
};

// 显示上传对话框
const showUploadModal = (kb: any) => {
  currentKnowledgeBase.value = kb;
  fileList.value = [];
  uploadModalVisible.value = true;
};

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  fileList.value = [file];
  return false;
};

// 移除文件
const handleRemove = () => {
  fileList.value = [];
};

// 处理上传确认
const handleUploadOk = async () => {
  if (!currentKnowledgeBase.value || fileList.value.length === 0) {
    return;
  }

  const file = fileList.value[0];
  console.log('file', file);
  const loadingKey = `upload_${Date.now()}`;

  try {
    message.loading({ content: '上传中...', key: loadingKey, duration: 0 });
    await uploadFileToKnowledgeBase(currentKnowledgeBase.value.id, file);
    message.success({ content: '上传成功', key: loadingKey });
    uploadModalVisible.value = false;
    fetchKnowledgeBases();
  } catch (error: any) {
    message.error({ content: error.message || '上传失败', key: loadingKey });
  }
};

// 处理上传取消
const handleUploadCancel = () => {
  uploadModalVisible.value = false;
};

// 显示问答对话框
const showQueryModal = (kb: any) => {
  currentKnowledgeBase.value = kb;
  queryText.value = '';
  chatMessages.value = [];
  queryModalVisible.value = true;
};

// 处理问答查询
const handleQuery = async () => {
  if (!queryText.value.trim() || answering.value) {
    return;
  }

  const question = queryText.value.trim();
  chatMessages.value.push({
    type: 'question',
    content: question,
  });
  queryText.value = '';
  answering.value = true;

  scrollToBottom();

  try {
    const res = await getCarKnowledgeAnswer(
      question,
      currentKnowledgeBase.value?.id,
    );
    console.log('res', res);
    // 使用新的返回格式
    const answer = res.finalAnswer || '抱歉，我无法回答这个问题';
    console.log('answer', answer);
    const processingTime = res.processingTime;

    chatMessages.value.push({
      type: 'answer',
      content: answer,
      processingTime,
    });
  } catch (error: any) {
    chatMessages.value.push({
      type: 'answer',
      content: `抱歉，发生错误: ${error.message || '未知错误'}`,
    });
  } finally {
    answering.value = false;
    scrollToBottom();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 监听聊天消息变化，自动滚动
watch(chatMessages, () => {
  scrollToBottom();
});

// 组件挂载时获取知识库列表
onMounted(() => {
  fetchKnowledgeBases();
});

// 处理状态切换
const handleStatusChange = (checked: any): void => {
  formState.status = checked ? 1 : 0;
};

// 显示搜索对话框
const showSearchModal = (kb: any) => {
  currentKnowledgeBase.value = kb;
  searchText.value = '';
  searchResults.value = [];
  searchModalVisible.value = true;
};

// 处理搜索
const handleSearch = async () => {
  if (!searchText.value.trim() || searchLoading.value) {
    return;
  }

  searchLoading.value = true;
  try {
    const res = await searchKnowledgeBase(
      searchText.value.trim(),
      5,
      currentKnowledgeBase.value?.id,
    );
    searchResults.value = Array.isArray(res) ? res : [];
  } catch (error: any) {
    message.error(error.message || '搜索失败');
    searchResults.value = [];
  } finally {
    searchLoading.value = false;
  }
};
</script>

<template>
  <div class="knowledge-base-container">
    <Row :gutter="16" class="mb-4">
      <Col :span="24">
        <Card>
          <template #title>知识库管理</template>
          <template #extra>
            <Button type="primary" @click="showCreateModal">
              <template #icon><PlusOutlined /></template>
              新增知识库
            </Button>
          </template>
          <p>管理您的知识库，上传文件并进行智能问答</p>
        </Card>
      </Col>
    </Row>

    <!-- 知识库列表 -->
    <Row :gutter="16">
      <Col :span="24">
        <Spin :spinning="loading">
          <div
            v-if="knowledgeBases.length === 0 && !loading"
            class="empty-container"
          >
            <Empty description="暂无知识库" />
          </div>
          <Row :gutter="16" v-else>
            <Col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="8"
              :xl="6"
              v-for="kb in knowledgeBases"
              :key="kb.id"
              class="mb-4"
            >
              <Card hoverable>
                <template #cover>
                  <div class="card-cover">
                    <BookOutlined class="card-icon" />
                    <Tag
                      :color="kb.status === 1 ? 'success' : 'error'"
                      class="status-tag"
                    >
                      {{ kb.status === 1 ? '启用' : '禁用' }}
                    </Tag>
                  </div>
                </template>
                <CardMeta :title="kb.name">
                  <template #description>
                    <div>
                      <p class="description">
                        {{ kb.description || '暂无描述' }}
                      </p>
                      <p>文档数量: {{ kb.documentCount || 0 }}</p>
                      <p>创建时间: {{ formatDate(kb.createTime) }}</p>
                    </div>
                  </template>
                </CardMeta>
                <div class="card-actions">
                  <Button
                    type="primary"
                    size="small"
                    @click="showUploadModal(kb)"
                  >
                    <template #icon><UploadOutlined /></template>
                    上传文件
                  </Button>
                  <Button
                    type="default"
                    size="small"
                    @click="showQueryModal(kb)"
                  >
                    <template #icon><CommentOutlined /></template>
                    知识问答
                  </Button>
                  <Button
                    type="default"
                    size="small"
                    @click="showSearchModal(kb)"
                  >
                    <template #icon><SearchOutlined /></template>
                    知识库搜索
                  </Button>
                  <Dropdown>
                    <template #overlay>
                      <Menu>
                        <MenuItem key="edit" @click="showEditModal(kb)">
                          <EditOutlined />
                          编辑
                        </MenuItem>
                        <MenuItem key="delete" @click="confirmDelete(kb)">
                          <DeleteOutlined />
                          删除
                        </MenuItem>
                      </Menu>
                    </template>
                    <Button size="small">
                      <template #icon><MoreOutlined /></template>
                    </Button>
                  </Dropdown>
                </div>
              </Card>
            </Col>
          </Row>
        </Spin>
      </Col>
    </Row>

    <!-- 创建/编辑知识库对话框 -->
    <Modal
      v-model:open="modalVisible"
      :title="modalMode === 'create' ? '新增知识库' : '编辑知识库'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <Form :model="formState" :rules="formRules" ref="formRef">
        <FormItem label="知识库名称" name="name">
          <Input
            v-model:value="formState.name"
            placeholder="请输入知识库名称"
          />
        </FormItem>
        <FormItem label="知识库描述" name="description">
          <Textarea
            v-model:value="formState.description"
            placeholder="请输入知识库描述"
            :rows="4"
          />
        </FormItem>
        <FormItem label="状态" name="status">
          <Switch
            v-model:checked="statusChecked"
            @change="handleStatusChange"
            checked-children="启用"
            un-checked-children="禁用"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 上传文件对话框 -->
    <Modal
      v-model:open="uploadModalVisible"
      title="上传文件"
      @ok="handleUploadOk"
      @cancel="handleUploadCancel"
      :ok-button-props="{ disabled: fileList.length === 0 }"
    >
      <p>将文件上传到知识库: {{ currentKnowledgeBase?.name }}</p>
      <Upload.Dragger
        v-model:file-list="fileList"
        name="file"
        :multiple="false"
        :before-upload="beforeUpload"
        @remove="handleRemove"
      >
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p class="ant-upload-hint">
          支持单个文件上传，推荐上传文本文件(.txt, .md, .csv等)
        </p>
      </Upload.Dragger>
    </Modal>

    <!-- 知识问答对话框 -->
    <Modal
      v-model:open="queryModalVisible"
      title="知识问答"
      width="700px"
      :footer="null"
    >
      <div class="query-container">
        <div class="query-header">
          <h3>{{ currentKnowledgeBase?.name }} - 知识问答</h3>
          <p>{{ currentKnowledgeBase?.description }}</p>
        </div>

        <div class="chat-container" ref="chatContainer">
          <div
            v-for="(msg, index) in chatMessages"
            :key="index"
            class="chat-message"
            :class="[msg.type]"
          >
            <div class="message-content">
              <div v-if="msg.type === 'question'" class="message-avatar">
                <UserOutlined />
              </div>
              <div v-else class="message-avatar">
                <RobotOutlined />
              </div>
              <div class="message-text">
                {{ msg.content }}
              </div>
            </div>
            <div v-if="msg.processingTime" class="message-time">
              处理耗时: {{ msg.processingTime }}ms
            </div>
          </div>
          <div v-if="answering" class="chat-message answer">
            <div class="message-content">
              <div class="message-avatar">
                <RobotOutlined />
              </div>
              <div class="message-text">
                <Spin size="small" />
              </div>
            </div>
          </div>
        </div>

        <div class="query-input">
          <InputSearch
            v-model:value="queryText"
            placeholder="请输入您的问题"
            enter-button="发送"
            size="large"
            :loading="answering"
            :disabled="answering"
            @search="handleQuery"
          />
        </div>
      </div>
    </Modal>

    <!-- 知识库搜索对话框 -->
    <Modal
      v-model:open="searchModalVisible"
      title="知识库搜索"
      width="700px"
      :footer="null"
    >
      <div class="search-container">
        <div class="search-header">
          <h3>{{ currentKnowledgeBase?.name }} - 知识库搜索</h3>
          <p>{{ currentKnowledgeBase?.description }}</p>
        </div>

        <div class="search-input">
          <InputSearch
            v-model:value="searchText"
            placeholder="请输入搜索关键词"
            enter-button="搜索"
            size="large"
            :loading="searchLoading"
            :disabled="searchLoading"
            @search="handleSearch"
          />
        </div>

        <div class="search-results">
          <Spin :spinning="searchLoading">
            <div
              v-if="searchResults.length === 0 && !searchLoading"
              class="empty-container"
            >
              <Empty description="暂无搜索结果" />
            </div>
            <div v-else class="result-list">
              <div
                v-for="(result, index) in searchResults"
                :key="index"
                class="result-item"
              >
                <div class="result-header">
                  <span class="result-id">ID: {{ result.id }}</span>
                  <span class="result-score"
                    >相关度: {{ (result.score * 100).toFixed(2) }}%</span
                  >
                </div>
                <div class="result-content">
                  <p class="result-text">{{ result.text }}</p>
                  <p class="result-excerpt">{{ result.excerpt }}</p>
                </div>
                <div class="result-footer">
                  <span class="result-baseid"
                    >知识库ID: {{ result.baseid }}</span
                  >
                </div>
              </div>
            </div>
          </Spin>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.knowledge-base-container {
  padding: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.empty-container {
  padding: 48px 0;
  text-align: center;
}

.card-cover {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  position: relative;
}

.card-icon {
  font-size: 48px;
  color: #1890ff;
}

.status-tag {
  position: absolute;
  top: 8px;
  right: 8px;
}

.description {
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-actions {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
}

.query-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.query-header {
  margin-bottom: 16px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 16px;
  height: 360px;
}

.chat-message {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.message-content {
  display: flex;
  max-width: 80%;
}

.chat-message.question .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1890ff;
  color: white;
}

.chat-message.question .message-avatar {
  background-color: #52c41a;
}

.message-text {
  color: #666;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: white;
  margin: 0 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-message.question .message-text {
  background-color: #d9f7be;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  align-self: flex-start;
}

.chat-message.question .message-time {
  align-self: flex-end;
}

.query-input {
  margin-top: auto;
}

.search-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.search-header {
  margin-bottom: 16px;
}

.search-input {
  margin-bottom: 16px;
}

.search-results {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  background-color: white;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.result-content {
  margin: 12px 0;
}

.result-text {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 8px;
}

.result-excerpt {
  color: #666;
  font-size: 13px;
  line-height: 1.4;
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}

.result-footer {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.result-score {
  color: #1890ff;
  font-weight: 500;
}
</style>
